package com.jltx.xq.simplewatch.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jltx.xq.simplewatch.R;
import com.jltx.xq.simplewatch.base.presenter.BasePresenter;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import cn.jltx.support.SupportFragment;

/**
 * @author jltxseo
 *         Created by junlintianxia on 2017/08/19.
 */

public abstract class BaseSupportFragment<T extends BasePresenter> extends SupportFragment{
    public T presenter;
    private View rootView;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter = initPresenter();
    }

    @Nullable
    @Override
    final public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(rootView == null){
            int contentViewId = provideContentViewId();
            rootView = inflater.inflate(contentViewId,container,false);
            ButterKnife.bind(this, rootView);
            initView(rootView,savedInstanceState);
        }else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        return rootView;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if(presenter != null){
            presenter.detachView();
        }
    }

    /**
     * 判断是否已经将对应的subscribe订阅者订阅到了eventBus总线上
     * @param subscribe
     * @return
     */
    public boolean isEventBusRegisted(Object subscribe){
        return EventBus.getDefault().isRegistered(subscribe);
    }

    /**
     * 注册subscribe订阅事件到eventBus总线
     * @param subscribe
     */
    public void registerEventBus(Object subscribe){
        if(!isEventBusRegisted(subscribe)){
            EventBus.getDefault().register(subscribe);
        }
    }

    /**
     * 取消subscribe订阅事件
     * @param subscribe
     */
    public void unregisterEventBus(Object subscribe){
        if(isEventBusRegisted(subscribe)){
            EventBus.getDefault().unregister(subscribe);
        }
    }

    public void setSwipeRefreshLayoutColor(SwipeRefreshLayout swipeRefreshLayout){
        swipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(getActivity(), R.color.colorPrimary));
    }

    //得到当前界面的布局文件id(由子类实现)
    protected abstract int provideContentViewId();

    // 实例化presenter
    public abstract T initPresenter();

    //初始化一下View
    public void initView(View rootView,Bundle savedInstanceState) {
    }

}
